import React, { useState, useEffect } from 'react';
import LoginPage from './components/LoginPage/LoginPage';
import RegisterPage from './components/RegisterPage/RegisterPage';
import MainLayout from './components/MainLayout/MainLayout';
import './App.css';

function App() {
  const [currentPage, setCurrentPage] = useState('login');
  const [isFirstPageLoaded, setIsFirstPageLoaded] = useState(false);

  // 检测第一个页面是否完全加载
  useEffect(() => {
    if (currentPage === 'login' && !isFirstPageLoaded) {
      // 等待所有资源加载完成
      const checkPageReady = () => {
        // 检查DOM是否完全渲染
        const isDOMReady = document.readyState === 'complete';
        
        // 检查是否有未加载的图片
        const images = document.querySelectorAll('img');
        const allImagesLoaded = Array.from(images).every(img => img.complete);
        
        // 检查CSS是否加载完成
        const stylesheets = document.querySelectorAll('link[rel="stylesheet"]');
        const allStylesLoaded = Array.from(stylesheets).every(link => {
          return link.sheet && !link.sheet.disabled;
        });

        if (isDOMReady && allImagesLoaded && allStylesLoaded) {
          // 额外等待一小段时间确保React组件完全渲染
          setTimeout(() => {
            // 通知Electron主进程页面已加载完成
            if (window.electronAPI && window.electronAPI.notifyPageLoaded) {
              window.electronAPI.notifyPageLoaded();
            }
            setIsFirstPageLoaded(true);
          }, 50);
        } else {
          // 如果还没完全加载，继续检查
          setTimeout(checkPageReady, 50);
        }
      };

      // 开始检查页面是否准备就绪
      checkPageReady();
    }
  }, [currentPage, isFirstPageLoaded]);

  const handleGoToRegister = () => {
    setCurrentPage('register');
  };

  const handleBackToLogin = () => {
    setCurrentPage('login');
  };

  const handleLogin = (user) => {
    // 登录成功，跳转到主页面
    // user 参数包含登录成功的用户信息
    if (user) {
      console.log('用户登录成功:', user);
      setCurrentPage('main');
    }
  };

  const handleRegister = () => {
    setCurrentPage('main');
  };

  return (
    <div className="App">
      {currentPage === 'login' && (
        <LoginPage 
          onGoToRegister={handleGoToRegister} 
          onLogin={handleLogin}
        />
      )}
      {currentPage === 'register' && (
        <RegisterPage 
          onBackToLogin={handleBackToLogin}
          onRegister={handleRegister}
        />
      )}
      {currentPage === 'main' && <MainLayout />}
    </div>
  );
}

export default App;
